# -*- encoding:utf-8 -*-
"""
    author: jyy 2018-08-24
"""
from elasticsearch import Elasticsearch
from elasticsearch import helpers
import os
import sys
# from datetime import datetime
import datetime
import subprocess
import getopt
# # 禁用安全请求警告
import urllib3
urllib3.disable_warnings()


class esManger:
    def __init__(self, addr):
        try:
            self.es = Elasticsearch(
                [addr],
                http_auth=('tsgz', 'OiPeUuUI3yfE'),
                port=443,
                use_ssl=True,
                ca_certs=False,
                verify_certs=False,
                timeout=120
            )
            self.type = 0
            if self.es.indices.exists_template('web_template'):
                pass
            else:
                pass
        except:
            self.es = Elasticsearch(
                [addr],
                port=9200,
                timeout=120
            )
            self.type = 1
            if self.es.indices.exists_template('web_template'):
                pass
            else:
                pass

    def delete_template(self, indexs):
        """循环删除模板"""
        for index in indexs:
            if self.es.indices.exists_template(index + '_template'):
                self.es.indices.delete_template(index + '_template')
            if self.es.indices.exists_template(index + '_template_black'):
                self.es.indices.delete_template(index + '_template_black')

    def check_template(self, indexs):
        """校验数据模板是否存在 不存在就创建"""
        for index in indexs:
            if not self.es.indices.exists_template(index + '_template'):
                with open(os.path.join(TEMPLATE_PATH, index + '_template.json'), 'r') as file:
                    data = file.read()
                self.es.indices.put_template(index + '_template', data)
            if index in ['filetracking', 'eventupload']:
                continue
            if not self.es.indices.exists_template(index + '_template_black'):
                with open(os.path.join(TEMPLATE_PATH, index + '_template_black.json'), 'r') as file:
                    data = file.read()
                self.es.indices.put_template(index + '_template_black', data)

    def check_white_index(self, indexs):
        """校验 白数据 当天索引 不存在就创建"""
        day = str(datetime.date.today()).replace('-', '')
        for index in indexs:
            if index == 'ptd':
                index_name = index + day
            else:
                index_name = index + day[:6] + '01'
            if not self.es.indices.exists(index_name):
                self.es.indices.create(index=index_name, ignore=[400, 404])

    def check_black_index(self, indexs):
        """校验 黑数据 当年索引 不存在就创建"""
        year = str(datetime.datetime.now().year)
        for index in indexs:
            if index in ['filetracking', 'eventupload']:
                continue
            index_name = "black_" + index + year
            if not self.es.indices.exists(index_name):
                self.es.indices.create(index=index_name, ignore=[400, 404])

    def delete_old_index(self, indexs):
        """PTD 删除白数据索引 周期为2天
           其他类型 删除白数据索引 周期为月"""
        ago = str(datetime.date.today() - datetime.timedelta(days=2)).replace('-', '')
        for index in indexs:
            if index == 'pacps':
                index_name = index + ago
            else:
                # 获取当前月份
                month = int(datetime.date.today().month)
                month = month - 1 if month != 1 else 12
                month = str(month) if month >= 10 else '0' + str(month)
                year = int(datetime.date.today().year) - 1 if month == 12 else int(datetime.date.today().year)
                index_name = index + str(year) + str(month) + '01'
            if self.es.indices.exists(index_name):
                self.es.indices.delete(index=index_name, ignore=[400, 404])

    def delete_all_index(self, indexs):
        """删除某一类型的所有索引"""
        for index in indexs:
            if self.es.indices.exists(index):
                self.es.indices.delete(index=index, ignore=[400, 404])

    def delete_all(self, ip):
        if self.type == 0:
            tmpres = os.popen('curl -k -u tsgz:OiPeUuUI3yfE -g \'https://%s/_cat/indices/\'' % ip).readlines()
            for tmp in tmpres:
                index_name = tmp.split()[2]
                print index_name
                if index_name.find("searchguard") == -1:
                    if self.es.indices.exists(index_name):
                        self.es.indices.delete(index=index_name, ignore=[400, 404])
        elif self.type == 1:
            subprocess.call('curl -XDELETE \'http://%s/*\'' % ip, shell=True)
        else:
            print "删除异常"
        # subprocess.call('curl -k -u tsgz:OiPeUuUI3yfE -XDELETE \'https://%s/*\'' % ip, shell=True)
    
    def es_reindex(self, indexs):
        body = {"query": {"match_all": {}}}   # 遍历原索引
        helpers.reindex(
            client=self.es,
            source_index=indexs[0],
            target_index=indexs[1],
            target_client=self.es,  # 新索引所在es
            query=body,
            scroll='1m')  # scroll的时间
        # 重建索引
        # chunk_size=5000, es传输docs时每块含有的docs数量
        print datetime.datetime.now().strftime("%H:%M:%S")
        self.es.indices.delete(index=indexs[0], ignore=[400, 404])
        print datetime.datetime.now().strftime("%H:%M:%S")


if __name__ == '__main__':
    try:
        # 同时支持短选项和长选项
        # opts, args = getopt.getopt(sys.argv[1:], "idDt:", ["path=", "url="])
        # 只支持短选项
        opts, args = getopt.getopt(sys.argv[1:], "idDmMRu:t:p:")
        if len(sys.argv) < 4:
            print """
                python esManger.py -i -u ip -t type1,type2.. -p templatePath
                python esManger.py -M -u ip -t type1,type2.. -p templatePath
                python esManger.py -m -u ip -t type1,type2..
                python esManger.py -d -u ip -t type1,type2..
                python esManger.py -D -u ip -t type1,type2..
                python esManger.py -R -u ip -t type1,type2..
                python esManger.py -D -u ip
                备注：
                -i : install 创建索引
                -m : delTemplate 删除索引模板
                -M : delTemplate and creatTemplate 删除模板并重新创建
                -d : delWhite 删除白数据索引
                -D : delAll 删除所有数据索引
                -u ：url es地址
                -t : type 要操作的数据类型（如：iep,pta,ptd...）
                -p : templatePath 模板地址
                -R : reindex索引
                """
        else:
            argv = []
            optes = []
            for opt, arg in opts:
                if opt == '-i':
                    optes.append(opt)
                    argv.append(arg)
                elif opt == "-d":
                    optes.append(opt)
                    argv.append(arg)
                elif opt == "-D":
                    optes.append(opt)
                    argv.append(arg)
                elif opt == "-m":
                    optes.append(opt)
                    argv.append(arg)
                elif opt == "-M":
                    optes.append(opt)
                    argv.append(arg)
                elif opt == "-R":
                    optes.append(opt)
                    argv.append(arg)
                elif opt == "-u":
                    optes.append(opt)
                    argv.append(arg)
                elif opt == "-t":
                    optes.append(opt)
                    argv.append(arg)
                elif opt == "-p":
                    optes.append(opt)
                    argv.append(arg)
            es = esManger(argv[1])
            if optes[0] == '-i':
                TEMPLATE_PATH = argv[3]
                es.delete_template(argv[2].split(','))
                es.check_template(argv[2].split(','))
                es.check_white_index(argv[2].split(','))
                es.check_black_index(argv[2].split(','))
            elif optes[0] == '-m':
                es.delete_template(argv[2].split(','))
            elif optes[0] == '-M':
                TEMPLATE_PATH = argv[3]
                es.delete_template(argv[2].split(','))
                es.check_template(argv[2].split(','))
            elif optes[0] == '-d':
                es.delete_old_index(argv[2].split(','))
            elif optes[0] == '-D':
                if len(sys.argv) > 4:
                    es.delete_all_index(argv[2].split(','))
                else:
                    es.delete_all(argv[1])
                    # subprocess.call('curl -k -u tsgz:OiPeUuUI3yfE -XDELETE \'https://%s/*\'' % argv[1], shell=True) 
            elif optes[0] == '-R':
                es.es_reindex(argv[2].split(','))
    except Exception, e:
        print e
